#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2018 crane <crane@his-pc>
#
# Distributed under terms of the MIT license.

"""

"""


class ListNode(object):
    def __init__(self, val, next=None):
        self.val = val
        self.next = next


class Solution:
    """
    @param head: The first node of linked list.
    @param n: An integer
    @return: The head of linked list.
    """
    def removeNthFromEnd(self, head, k):
        # write your code here
        pre, last_kth = self.last_kth_and_pre(head, k)

        if last_kth is None:
            # 链表不足k个元素
            return head

        if last_kth is head:
            # 倒数第k是head
            ret = head.next
            head.next = None
            return ret

        pre.next = last_kth.next
        last_kth.next = None
        return head

    def last_kth_and_pre(self, head, k):
        fast = head

        while fast and k:
            k -= 1
            fast = fast.next

        if k != 0:
            return None, None

        slow = head
        pre = slow

        while fast:
            pre = slow
            slow = slow.next
            fast = fast.next

        return pre, slow


def main():
    print("start main")

if __name__ == "__main__":
    main()
